In [1]:
print([i for i in range(1, 100+1) if i%3==0 or i%5==0])
In [2]:
num = 15
result = ""
if num % 3 == 0:
result += "Beer"
if num % 5 == 0:
result += "Chichen"
print(result)
In [3]:
result = []
for i in range(1, 100+1):
word = ''
if i % 3 == 0:
word += "Beer"
if i % 5 == 0:
word += "Chicken"
result.append(word)
print(result)
In [4]:
beer_list = [
"Beer" if x % 3 == 0 else ""
for x
in range(1, 100+1)
]
chicken_list = [
"Chicken" if x % 5 == 0 else ""
for x
in range(1, 100+1)
]
print([
beer_list[i] + chicken_list[i]
for i
in range(100)
])
In [7]:
def word_add_num(count, first_num, first_word, second_num, second_word):
first_list = [
first_word if i % first_num == 0 else ""
for i
in range(1, count+1)
]
second_list = [
second_word if i % second_num == 0 else ""
for i
in range(1, count+1)
]
return [
first_list[i] + second_list[i]
for i
in range(count)
]
#함수이기 때문에 return을 해주어야 한다.
In [9]:
print(word_add_num(100, 3, "ki", 7, "poy"))
In [ ]:
In [13]:
def reverse(word):
reversed_word = ""
for i in range(len(word)):
reversed_word += word[len(word)-1-i]
return reversed_word
def is_palindrome(word):
return word == reverse(word)
In [15]:
is_palindrome("기러기")
Out[15]:
In [17]:
is_palindrome("소주만병만주소")
Out[17]:
In [18]:
is_palindrome("김기표")
Out[18]:
In [19]:
"자일리톨껌"[::-1]
Out[19]:
In [20]:
def reverse(word):
return word[::-1]
def is_palindrome(word):
return word == reverse(word)
In [21]:
is_palindrome("기러기")
Out[21]:
In [22]:
is_palindrome("PCA")
Out[22]:
In [23]:
is_palindrome("ABCBA")
Out[23]:
In [24]:
def is_palindrome(word):
return word == word[::-1]
In [25]:
is_palindrome("수박이박수")
Out[25]:
In [26]:
(lambda x: x == x[::-1])("손가방")
Out[26]:
In [27]:
(lambda x: x == x[::-1])("고기고")
Out[27]:
In [ ]:
In [29]:
def word_split(sentence, sperat=" "):
word_list = []
word = ""
for char in sentence:
if char == " ":
word_list.append(word)
word = ""
else:
word += char
return word_list
word_split("오늘은 날씨가 참 맑구나.")
Out[29]:
In [30]:
def word_split(sentence, sperat=" "):
word_list = []
word = ""
for char in sentence + " ": # " " 이거를 추가해야 끝까지 출력이 됩니다.
if char == " ":
word_list.append(word)
word = ""
else:
word += char
return word_list
word_split("오늘은 날씨가 참 맑구나.")
Out[30]:
In [33]:
def word_split(sentence, seperate=" "):
word_list =[]
word = ""
for char in sentence:
if char == " ":
word_list.append(word)
word=""
else:
word += char
if word != "":
word_list.append(word)
return word_list
word_split("오늘은 날씨가 참 맑구나.")
Out[33]:
In [35]:
def word_split(sentence, seperate=" "):
word_list = []
word = ""
for char in sentence:
if char == seperate:
word_list.append(word)
word = ""
else:
word += char
if word != "":
word_list.append(word)
return word_list
word_split("오늘은 왠지 날씨가 참 맑은가.", "가")
Out[35]:
In [ ]:
In [36]:
def word_join(word_list, seperate=" "):
result = ""
for word in word_list:
result += word
result += seperate
return result
word_join(["오늘은", "정말", "공부가", "하기", "싫다고", "말하면", "안", "되고", "그냥", "그래요"])
Out[36]:
In [ ]:
In [37]:
def word_join_2(word_list, seperate=" "):
result = ""
for index, word in enumerate(word_list):
result += word
if not index == len(word_list)-1:
result += seperate
return result
word_join_2(["당신은", "존재", "자체로", "소중합니다."])
Out[37]:
In [ ]:
In [49]:
word_list = "카페나 도서관이나 공부하기는 참 좋다.".split(" ")
word_list
Out[49]:
In [52]:
[word for word in word_list if not word == ""]
Out[52]:
In [54]:
" ".join(["카페나", "도서관이나", "공부하기는", "참", "좋다."])
Out[54]:
In [ ]:
In [55]:
"지진무서워".replace("지진", "홍수")
Out[55]:
In [ ]:
In [56]:
user_list = [
["김기표", "주소1"],
["김깊효", "주소2"],
]
In [60]:
user_dict_list = []
for user in user_list:
name = user[0]
address = user[1]
user_dict = {
"name": name,
"address": address,
}
user_dict_list.append(user_dict)
user_dict_list
Out[60]:
In [ ]:
In [65]:
def get_user_dict(user):
return {
"name": user[0],
"address": user[1]
}
get_user_dict(user_list)
Out[65]:
In [68]:
[
{
"name": user[0],
"address": user[1]
}
for user
in user_list
]
Out[68]:
In [ ]:
In [69]:
with open("./users.csv", "r") as f: #기존에 users_csv에 사용자 정보가 있다면
user_list = []
for line in f.readlines():
user_list.append({
"name": line.split(",")[0],
"address": line.split(",")[1].replace("\n", "")
})
user_list
In [70]:
with open("./users.csv", "r") as f:
user_list = [
{
"name": line.split(",")[0],
"address": line.split(",")[1].replace("\n", "")
}
for line
in f.readlines()
]
user_list
In [71]:
def preprocess(phonenumber):
phonenumber_process_dict = {
"공": 0,
"영": 0,
"일": 1,
"이": 2,
"삼": 3,
"사": 4,
"오": 5,
"육": 6,
"칠": 7,
"팔": 8,
"구": 9,
"-": "",
" ": "",
}
for key, value in phonenumber_process_dict.items(): #items는 key, value를 한 번에 뽑을 때 사용된다.
phonenumber = phonenumber.replace(key, str(value))
return phonenumber
preprocess("공일공육이35-삼삼1구")
Out[71]:
In [72]:
with open("./phonenumber.txt", "r") as input_file: #전처리 대상 텍스트 파일 있을 때
result = [
preprocess(line.replace("\n", ""))
for line
in input_file.readlines()
]
result
In [73]:
with open("./phonenumber.txt", "r") as input_file:
with open("./phonenumber_preprocessed.txt", "w") as output_file:
[
output_file.write(
preprocess(line.replace("\n", "")) + "\n"
)
for line
in input_file.readlines()
]
객체 지향 프로그래밍 ( Object Oriented Programming )
함수형 프로그래밍 => Lambda, Lambda Operator, List Comprehension
In [77]:
class Student(): # Student() => __init__ 함수가 실행되는 것
__campus = "패스트캠퍼스" #변수를 밖에서 부를 수는 있지만 안 부르는 것이 약속
def __init__(self, name, age): # init => initialize ( 초기화하다 )
self.name = name
self.age = age
print("학생 {name}({age}) 가 태어났습니다.".format(
name=self.name,
age=self.age
))
# 자기소개를 할 수 있다.
def introduce(self):
print("안녕하세요, 저는 {campus}에 다녔던 {age}살 {name} 입니다.".format(
campus=self.__campus,
age=self.age,
name=self.name,
))
In [78]:
kimkipoy = Student("김기표", 29)
In [79]:
kimkipoy.introduce()
In [82]:
kimkipoy.campus = "경쟁사"
kimkipoy.introduce()
In [83]:
kimkipoy #_Student__campus 이와 같은 형태로 변수가 바뀌었다.
dir(kimkipoy)
Out[83]:
In [84]:
kimkipoy._Student__campus = "경쟁사2"
kimkipoy.introduce()
In [ ]:
In [85]:
class Rectangle():
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def girth(self):
return 2 * (self.width + self.height)
def is_bigger(self, another):
if self.area() - another.area() >= 0:
print("내가 더 큼")
else:
print("내가 더 작음")
In [86]:
rec1 = Rectangle(10, 20)
rec2 = Rectangle(30, 10)
rec1.is_bigger(rec2)
In [87]:
class Rectangle():
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return "면적은 {area} 입니다.".format(
area=self.width * self.height
)
def girth(self):
return "둘레는 {girth} 입니다".format(
girth = self.width * 2 + self.height * 2,
)
def is_bigger(self, another):
my_area = self.area()
another_area = another.area()
return my_area > another_area
In [88]:
my_rectangle = Rectangle(100, 200)
another_rect = Rectangle(10, 20)
my_rectangle.is_bigger(another_rect)
Out[88]:
In [89]:
class Person():
def __init__(self, name, money):
self.name = name
self.money = money
def send_money(self, to, amount):
print("{to_name}한테 {amount}원 만큼 돈을 보냅니다.".format(
to_name=to.name,
amount=amount,
))
self.money -= amount
to.money += amount
In [90]:
person1 = Person("돈 빌려준 사람", 1000)
person2 = Person("돈 빌린 사람", 500)
In [91]:
person2.send_money(person1, 500)
In [92]:
person1.money, person2.money
Out[92]:
In [93]:
class Student():
def __init__(self, name, address):
self.name = name
self.address = address
def introduce(self):
print("저는 {address}에 살고 있는 {name}입니다.".format(
address=self.address,
name=self.name,
))
In [94]:
student = Student("김기표", "경기도 안양시")
student.introduce()
In [95]:
with open("../users.csv", "r") as f: #users.csv라는 사용자 정보 있을 때
student_list = [
Student(
line.split(",")[0],
line.split(",")[1].replace("\n", "")
)
for line
in f.readlines()
]
for student in student_list:
student.introduce()